package org.git.movie.videojiexi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.git.movie.videojiexi.enums.VideoChannel;
import org.git.movie.videojiexi.model.VideoModel;
import org.git.movie.videojiexi.service.VideoService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service("WeishiServiceImpl")
public class WeishiServiceImpl implements VideoService {
    private static Logger log = LoggerFactory.getLogger(WeishiServiceImpl.class);
    /**
     * 如何获取视频地址：
     * 在视频上-->点击鼠标右键-->复制视频页面地址
     * @param url
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public VideoModel parseUrl(String url, String userAgent) throws Exception {
            String useUrl = null;
            if(url.startsWith("https://h5.weishi.qq.com/weishi/feed/")){
                useUrl = url.substring(0,url.indexOf("?")+1);
                useUrl +=  "orifrom=message&from=pc&orifrom=pc";
            }
            log.info(useUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Connection", "keep-alive");
        headers.put("authority", "h5.weishi.qq.com");
       // headers.put("path", "h5.weishi.qq.com");
        if(userAgent == null || userAgent.length() ==0){
            userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36";
        }
        headers.put("User-Agent", userAgent);


        Document doc = null;
        try {
            doc = Jsoup.connect(useUrl).headers(headers).get();
        } catch (Exception e) {
            ///e.printStackTrace();
            System.out.println(e.getMessage()+":--------------->"+useUrl);
        }
        if( doc == null )return null;
//        System.out.println(doc.toString());

        Elements elScripts = doc.getElementsByTag("script");
        String vcontent = null;
        for(Element scriptItem :elScripts){
            String content =  scriptItem.data().toString();
            if(content != null && content.indexOf("window.syncData =") >= 0){

                vcontent = content.trim();
                vcontent = vcontent.replace("window.syncData =","");
                if(vcontent.endsWith(";")){
                    vcontent =vcontent.substring(0,vcontent.length() -1);
                }
                break;
            }
        }
        log.info(vcontent==null?"null":vcontent);
        JSONObject jsonObject = JSON.parseObject(vcontent);
        JSONArray feeds =jsonObject.getJSONArray("feeds");
        JSONObject video =feeds.getJSONObject(0);

        JSONObject video_spec_urls = video.getJSONObject("video_spec_urls");
        Set<String> keys = video_spec_urls.keySet();
        String downloadUrl =  null;
        for(String key :keys){
            JSONObject lastVideo = video_spec_urls.getJSONObject(key);
            downloadUrl =  lastVideo.getString("url");
            break;
        }


        JSONObject share_info = video.getJSONObject("share_info");
        JSONObject body_map = share_info.getJSONObject("body_map");
        JSONObject body_map0 = body_map.getJSONObject("0");
        String title = body_map0.getString("title");


        VideoModel rep = new VideoModel();
////        rep.setCover(picUrl);
////        rep.setFileType(fileType);
        rep.setPlayAddr(downloadUrl);
        rep.setChannel(VideoChannel.WEISHI);
        rep.setName(title);

        return rep;
    }



    private String getVids(String url){
        String[] arUrl = url.split(".html")[0].split("/");
        return arUrl[arUrl.length-1];
    }

    public static void main(String[] args) throws Exception {
        VideoModel rep =   new WeishiServiceImpl().parseUrl("https://h5.weishi.qq.com/weishi/feed/76WnSGZYg1IhPcZBB/wsfeed?wxplay=1&id=76WnSGZYg1IhPcZBB&spid=1579874477460819&qua=v1_iph_weishi_6.4.1_630_app_a&chid=100000014&pkg=3670&attach=cp_reserves3_1000000012&from=message","");
        log.info(JSON.toJSONString(rep));


//        VideoModel rep2 =   new TencentQqServiceImpl().parseUrl("https://m.v.qq.com/play.html?vid=x3037227u8z","");
//        log.info(JSON.toJSONString(rep2));


    }
}
